<?php	
class ListController extends Zend_Controller_Action
{
	public function init()
	{
		//Helper_Authenticate::checkLogin();
	}

	public function indexAction()
	{
		$form = new Application_Form_List_OrderForm(array('Name', 'Owner Name'));
		$this->view->form = $form;

		$list = new Application_Model_DbTable_List();
		$this->view->list = $list->fetchAll();

	}

	public function addAction()
	{
		$form = new Application_Form_List();
		$form->submit->setLabel('Add new Contact List');
		$this->view->form = $form;


		if ($this->getRequest()->isPost())
		{
			$formData = $this->getRequest()->getPost();

			if ($form->isValid($formData))
			{
				$mytoken = Application_Helper_Session::get('token', '');
				$token = $form->getValue('token');

				if($token == $mytoken)
				{
					Application_Helper_Session::remove('token');

					$data = $this->getRequest()->getParams();

					$list = new Application_Model_DbTable_List();
					$list->addList($data);

					$this->_helper->redirector('index');
				}
				else
				{
					$this->_helper->redirector('index');
				}
			}
			else
			{
				$form->populate($formData);
			}
		}
		else
		{
			$values = array();
			$token = time();
			Application_Helper_Session::set('token', $token);

			$values['token'] = $token;

			$form->populate($values);

		}

	}

	public function editAction()
	{
		$form = new Application_Form_List();
		$form->submit->setLabel('Edit Contact List');
		$this->view->form = $form;
		
		$list = new Application_Model_DbTable_List();
		$id = $this->_getParam('id', 0);
		$values = $list->getList($id);
		
			
		if ($this->getRequest()->isPost())
		{
			$formData = $this->getRequest()->getPost();
			
			if ($form->isValid($formData))
			{
				$mytoken = Application_Helper_Session::get('token', '');
				$token = $form->getValue('token');

				if ($mytoken == $token)
				{
					Application_Helper_Session::remove('token');
					
					$list = new Application_Model_DbTable_List();
					$list->updateList($id, $formData);
					$this->_helper->redirector('index');
				}
			}
			else
			{
				$form->populate($formData);
			}
		}
		else
		{
			$token = time();
			
			Application_Helper_Session::set('token', $token);
				
			$values['token'] = $token;
				
			$form->populate($values);	
		}
	}

	public function deleteAction()
	{
		if ($this->getRequest()->isPost()) {

			$del = $this->getRequest()->getPost('del');

			if ($del == 'Yes') {

				$id = $this->getRequest()->getPost('id');

				$list = new Application_Model_DbTable_List();
				$list->deleteList($id);
			}

			$this->_helper->redirector('index');

		} else {

			$id = $this->_getParam('id', 0);

			$list = new Application_Model_DbTable_List();

			$this->view->list = $list->getList($id);
		}
	}	
}